import { reportForms } from "@/api/index";
import { table } from "@/api";
import { mapState, mapActions, mapGetters } from "vuex";
import { columnsScreen, derives, multi } from "./columns";
import RmsDetail from "@components/table/dialog/RmsDetail"
import ExportExcelAction from "../Export/ExportExcelAction"
export default {
  name: "rmsDetails",
  data () {
    return {
      total: 0,
      pageSizeOptions: [10, 20, 50, 100, 500],
      pageNo: 1,
      pageSize: 10,
      combineTr: 7,
      shipType: '',
      shipName: '',
      dialogVisible: false,
      loading: false,
      particularYear: '',
      time: '',
      pickDate: '',
      currentYear: '',
      currentMonth: '',
      currentTime: '',
      params: {
        customerName: "",
        carrierName: "",
        page: 1,
        size: 10,
      },
      paramsReset: {
        customerName: "",
        carrierName: "",
        page: 1,
        size: 10,
      },
      pickerOptions: {
        onPick: this.getPickDate,
        disabledDate: this.disabledDate
      },
      derive: {},
      shipData: {},
      shipTime: {},
      allTotal: {},
      currentTotal: {},
      tableData: [],
      fromTime: [],
      isCloseList: [{
        label: '是',
        value: true
      }, {
        label: '否',
        value: false
      }],
      orderTypeOption: [{
        label: '经销商直发',
        value: '经销商直发'
      }, {
        label: '干线直发',
        value: '干线直发'
      }, {
        label: 'OEM直发',
        value: 'OEM直发'
      }],
      ModeOptions: [{
        label: '全部',
        value: ''
      }, {
        label: '零担',
        value: 1
      }, {
        label: '整车',
        value: 2
      }],
      yearList: [
        { id: 0, name: "" },
        { id: 1, name: "" }
      ],
      columns: [],
      userInfo: sessionStorage.getItem('userInfo'),
      userId: JSON.parse(sessionStorage.getItem('userInfo')).userId
    };
  },
  computed: {
    ...mapState({
      menuId: (state) => state.menu.menu.menuId
    }),
    ...mapGetters('rmsTable', ['getRmsFirstRecordSearch']),
    firstNewRecordSearch () {
      return this.getRmsFirstRecordSearch(this.userId, this.menuId)
    },
  },
  mounted () {
    setTimeout(() => {
      this.columns = columnsScreen(this.menuId);
      this.derive = derives(this.menuId);
      this.locationInHone();
    }, 1500);
  },
  methods: {
    ...mapActions({
      recordRmsNewFilters: "rmsTable/recordRmsNewFilters",
    }),
    // 是否带参
    locationInHone () {
      let now = new Date();
      this.currentYear = now.getFullYear()
      this.currentMonth = now.getMonth() + 1;
      this.currentTime = String(now.getFullYear()) + (this.currentMonth < 10 ? '0' + String(this.currentMonth) : String(this.currentMonth));
      this.yearList[0].name = this.currentYear;
      this.yearList[1].name = this.currentYear - 1;
      if (this.menuId == 311) {
        delete this.params.carrierName
      } else if (this.menuId == 330) {
        delete this.params.customerName
      } else {
        delete this.params.carrierName
        delete this.params.customerName
      }
      if (this.menuId == 333 || this.menuId == 334) {
        this.params = { ...this.firstNewRecordSearch, ...this.params }
        this.fromTime = [this.params.queryStartTime ? this.params.queryStartTime : '',
        this.params.queryEndTime ? this.params.queryEndTime : '']
      }
      this.search(2);
    },
    // 切换页数大小
    handleSizeChange () {
      this.search(2);
    },
    // 分页
    handleCurrentChange () {
      this.search(2);
    },
    // 查询
    async search (type) {
      this.params.page = type == 1 ? 1 : this.pageNo,
        this.pageNo = type == 1 ? 1 : this.pageNo,
        this.params.size = this.pageSize
      this.tableData = []
      this.loading = true
      if (this.menuId == 333 || this.menuId == 334) {
        if (!this.params.queryStartTime || !this.params.queryEndTime) {
          delete this.params.queryStartTime
          delete this.params.queryEndTime
        }
        this.recordRmsNewFilters({ userId: this.userId, menuId: this.menuId, data: JSON.parse(JSON.stringify(this.params)) })
      }
      let { data } = await reportForms.rmsList(this.params, this.menuId)
      let datas = data.data
      let code = data.code
      if (code === 0) {
        this.loading = false
        this.tableData = datas.records;
        this.allTotal = datas.allTotal
        this.currentTotal = datas.currentTotal
        this.total = datas.total;
      } else {
        this.loading = false
        this.tableData = []
      }
    },
    selectMonth (e) {
      console.log(e)
      if (e) {
        this.params.queryStartTime = this.$moment(this.time[0]).format("YYYYMM");
        this.params.queryEndTime = this.$moment(this.time[1]).format("YYYYMM");
      } else {
        this.params.queryStartTime = this.currentTime;
        this.params.queryEndTime = this.currentTime;
      }
    },
    clearYear (e) {
      this.params.year = e;
    },
    // 导出
    async handleExport () {
      if (!this.tableData.length) {
        this.$message.warning("没有可要导出的数据！");
        return false;
      }
      let args = JSON.parse(JSON.stringify(this.params))
      args.page = 1
      let params = {
        args: { ...args },
        name: this.derive.name,
        type: this.derive.type
      };
      await table.submitFormContainer(`/export/task`, params);
      this.searchCount();
      this.$nextTick(() => {
        this.$message.success("导出功能正在后台执行中，请稍后去“导出文件”下载中查看！");
      });
    },
    // 查询导出未读数
    ...mapActions({
      searchCount: "login/exportCount"
    }),
    //排序
    sortChange (val) {
      let name = val.prop
      this.params.sort = []
      this.params.sort = [{
        asc: false,
        name: ''
      }]
      if (val.order == 'descending') {
        this.params.sort[0].asc = false
        this.params.sort[0].name = val.prop
      } else if (val.order == 'ascending') {
        this.params.sort[0].asc = true
        this.params.sort[0].name = val.prop
      } else {
        delete this.params.sort
      }
      this.search(1);
    },
    // 清除
    resetForm () {
      this.time = []
      delete this.params.year;
      this.particularYear = '';
      this.fromTime = ''
      delete this.params.sort
      delete this.params.contractNo
      this.params = this.paramsReset
      if (this.menuId == 333 || this.menuId == 334) {
        this.recordRmsNewFilters({ userId: this.userId, menuId: this.menuId, data: this.params })
      }
      this.locationInHone();
    },
    dialog (data) {
      this.dialogVisible = true;
      this.shipTime = {
        queryStartTime: this.params.queryStartTime,
        queryEndTime: this.params.queryEndTime
      }
      this.shipData = data;
    },
    dialogMulti (data, name) {
      this.shipType = multi(this.menuId, name, 1)
      this.shipName = multi(this.menuId, name, 2)
      this.dialogVisible = true;
      this.shipTime = {
        queryStartTime: this.params.queryStartTime,
        queryEndTime: this.params.queryEndTime
      }
      this.shipData = data.id;
    },
    handleClose () {
      this.shipData = {}
      this.dialogVisible = false;
    },
    //限制筛选时效一年
    getPickDate (pick) {
      this.pickDate = pick;
    },
    //时间
    fromTimeGive (val) {
      console.log(val)
      this.params.queryStartTime = val ? val[0] : ''
      this.params.queryEndTime = val ? val[1] : ''
      if (!this.params.queryStartTime || !this.params.queryEndTime) {
        delete this.params.queryStartTime
        delete this.params.queryEndTime
      }
      this.recordRmsNewFilters({ userId: this.userId, menuId: this.menuId, data: JSON.parse(JSON.stringify(this.params)) })
    },
    disabledDate (date) {
      const { minDate, maxDate } = this.pickDate;
      if (minDate && !maxDate) {
        const diff = Math.abs(minDate.valueOf() - date.valueOf());
        if (diff > 1000 * 3600 * 24 * 365) {
          return true;
        }
      }
    },
    toFixeTwoPercent (num) {
      // 小数转百分比，保留两位小数
      num = typeof num === 'undefined' ? 0 : num
      num = num * 100 + ''
      if (num.indexOf('.') === -1) {
        num = num + '.00%'
      } else if (num.split('.')[1].length === 1) {
        num = num + '0%'
      } else {
        num = (num * 1) + '%'
      }
      return num
    },
    textTyep (name, data) {
      let text
      if (data && name != 'countScoreRate') {
        switch (name) {
          case 'countPickOntimeRate':
            text = '提货准时运单' + (data.device.countPickOntime ? data.device.countPickOntime : '0') + '/运单总数' + data.total.totalWaybillExclude
            break;
          case 'countPickTimeOutRate':
            text = '提货超时运单' + (data.device.countPickTimeOut ? data.device.countPickTimeOut : '0') + '/运单总数' + data.total.totalWaybillExclude
            break;
          case 'countDeliverOntimeRate':
            text = '送货准时运单' + (data.device.countDeliverOntime ? data.device.countDeliverOntime : '0') + '/运单总数' + data.total.totalWaybillExclude
            break;
          case 'countDeliverTimeOutRate':
            text = '送货超时运单' + (data.device.countDeliverTimeOut ? data.device.countDeliverTimeOut : '0') + '/运单总数' + data.total.totalWaybillExclude
            break;
          case 'countSignOntimeRate':
            text = '签收准时运单' + (data.device.countSignOntime ? data.device.countSignOntime : '0') + '/运单总数' + data.total.totalWaybill
            break;
          case 'countSignTimeOutRate':
            text = '已签收超时率' + (data.rate.receivedTimeoutRate ? data.rate.receivedTimeoutRate + '%' : '0%') + ' | 未签收超时率' + (data.rate.notReceivedTimeoutRate ? data.rate.notReceivedTimeoutRate + '%' : '0%')
            break;
          case 'countGoodsIntactRate':
            text = '货物完好运单' + (data.sign.countGoodsIntact ? data.sign.countGoodsIntact : '0') + '/已签收运单' + data.sign.countSign
            break;
          case 'countExceptionRate':
            text = '货物异常运单' + (data.sign.countException ? data.sign.countException : '0') + '/已签收运单' + data.sign.countSign
            break;
          case 'countReceiptOntimeRate':
            text = '回单准时运单' + (data.device.countReceiptOntime ? data.device.countReceiptOntime : '0') + '/运单总数' + data.total.totalWaybillExclude
            break;
          case 'countReceiptTimeoutRate':
            text = '已回单超时率' + (data.rate.receiptTimeoutRate ? data.rate.receiptTimeoutRate + '%' : '0%') + ' | 未回单超时率' + (data.rate.notReceiptTimeoutRate ? data.rate.notReceiptTimeoutRate + '%' : '0%')
            break;
        }
      }
      return text
    },
    showSummary (menuId) {
      let Booleans
      if (menuId == 367 || menuId == 368 || menuId == 318 || menuId == 332) {
        Booleans = false
      } else {
        Booleans = true
      }
      return Booleans
    },
    digitalConversion (data) {
      let value
      if (data == 100) {
        value = data + '%'
      } else if (data == 0 || !data) {
        value = '0%'
      } else {
        value = data + '%'
      }
      return value
    },
    conversion (val) {
      return JSON.stringify(val ? val : 0).replace(/\d(?=(\d{3})+\.)/g, '$&,');
    },
    getSummaries (param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        const value = JSON.stringify(this.currentTotal) != '{}' ? this.currentTotal[column.property] : 0;
        const values = JSON.stringify(this.allTotal) != '{}' ? this.allTotal[column.property] : 0;
        let el
        if (index === 0) {
          el = <p>本页合计：<br /><br />总合计：</p> // 主要代码
          sums[index] = el
          return;
        }
        if (column.label == '收入（元）') {
          el = <p>{{ text: this.conversion(this.currentTotal.totalAmountIncome) }}<br /><br />{{ text: this.conversion(this.allTotal.totalAmountIncome) }}</p>
        } else if (column.label == '异常收入（元）') {
          el = <p>{{ text: this.conversion(this.currentTotal.totalAmountAbnormalIncome) }}<br /><br />{{ text: this.conversion(this.allTotal.totalAmountAbnormalIncome) }}</p>
        } else if (column.label == '异常成本（元）') {
          el = <p>{{ text: this.conversion(this.currentTotal.totalAmountAbnormalCost) }}<br /><br />{{ text: this.conversion(this.allTotal.totalAmountAbnormalCost) }}</p>
        } else if (column.label == '运单数（单）') {
          el = <p>{{ text: this.conversion(this.currentTotal.totalWaybill) }}<br /><br />{{ text: this.conversion(this.allTotal.totalWaybill) }}</p>
        } else if (column.label == '绑定设备运单数（单）') {
          el = <p>{{ text: this.conversion(this.currentTotal.countUseDevice) }}<br /><br />{{ text: this.conversion(this.allTotal.countUseDevice) }}</p>
        } else if (column.label == '已签收数（单）') {
          if (this.menuId == 317 || this.menuId == 331) {
            el = <p>{{ text: this.conversion(this.currentTotal.countDeviceSign) }}<br /><br />{{ text: this.conversion(this.allTotal.countDeviceSign) }}</p>
          } else {
            el = <p>{{ text: this.conversion(this.currentTotal.countSign) }}<br /><br />{{ text: this.conversion(this.allTotal.countSign) }}</p>
          }
        } else if (column.label == '发货单数') {
          el = <p>{{ text: this.currentTotal.totalWaybill }}<br /><br />{{ text: this.allTotal.totalWaybill }}</p>
        } else if (column.label == '签收率（%）') {
          el = <p>{{ text: this.currentTotal.signRate + '%' }}<br /><br />{{ text: this.allTotal.signRate + '%' }}</p>
        } else if (column.label == '已回单数（单）') {
          el = <p>{{ text: this.currentTotal.countReceipt }}<br /><br />{{ text: this.allTotal.countReceipt }}</p>
        } else if (column.label == '回单率（%）') {
          el = <p>{{ text: this.currentTotal.receiptRate + '%' }}<br /><br />{{ text: this.allTotal.receiptRate + '%' }}</p>
        } else if (column.label == '8小时内签收率（%）') {
          el = <p>{{ text: this.currentTotal.countLess8Rate + '%' }}<br /><br />{{ text: this.allTotal.countLess8Rate + '%' }}</p>
        } else if (column.label == '8-24小时内签收率（%）') {
          el = <p>{{ text: this.currentTotal.countLess24Rate + '%' }}<br /><br />{{ text: this.allTotal.countLess24Rate + '%' }}</p>
        } else if (column.label == '24小时以上签收率（%）') {
          el = <p>{{ text: this.currentTotal.countmore24Rate + '%' }}<br /><br />{{ text: this.allTotal.countmore24Rate + '%' }}</p>
        } else if (column.label == '成本率（%）') {
          el = <p>{{ text: this.conversion(this.currentTotal.amountCostRate) + '%' }}<br /><br />{{ text: this.conversion(this.allTotal.amountCostRate) + '%' }}</p>
        } else if (column.label == '利润率（%）') {
          el = <p>{{ text: this.conversion(this.currentTotal.profitsRate) + '%' }}<br /><br />{{ text: this.conversion(this.allTotal.profitsRate) + '%' }}</p>
        } else if (column.label == '成本（元）') {
          el = <p>{{ text: this.conversion(this.currentTotal.totalAmountCost) }}<br /><br />{{ text: this.conversion(this.allTotal.totalAmountCost) }}</p>
        } else if (column.label == '利润（元）') {
          el = <p>{{ text: this.conversion(this.currentTotal.profits) }}<br /><br />{{ text: this.conversion(this.allTotal.profits) }}</p>
        } else if (column.label == '零担费（元）') {
          el = <p>{{ text: this.conversion(this.currentTotal.totalFeeDivide) }}<br /><br />{{ text: this.conversion(this.allTotal.totalFeeDivide) }}</p>
        } else if (column.label == '整车费（元）') {
          el = <p>{{ text: this.conversion(this.currentTotal.totalFeeWhole) }}<br /><br />{{ text: this.conversion(this.allTotal.totalFeeWhole) }}</p>
        } else if (column.label == '提货费（元）') {
          el = <p>{{ text: this.conversion(this.currentTotal.totalFeePick) }}<br /><br />{{ text: this.conversion(this.allTotal.totalFeePick) }}</p>
        } else if (column.label == '送货费（元）') {
          el = <p>{{ text: this.conversion(this.currentTotal.totalFeeDeliver) }}<br /><br />{{ text: this.conversion(this.allTotal.totalFeeDeliver) }}</p>
        } else if (column.label == '装货费（元）') {
          el = <p>{{ text: this.conversion(this.currentTotal.totalFeeLoad) }}<br /><br />{{ text: this.conversion(this.allTotal.totalFeeLoad) }}</p>
        } else if (column.label == '卸货费（元）') {
          el = <p>{{ text: this.conversion(this.currentTotal.totalFeeUnload) }}<br /><br />{{ text: this.conversion(this.allTotal.totalFeeUnload) }}</p>
        } else if (column.label == '补充费用（元）') {
          el = <p>{{ text: this.conversion(this.currentTotal.totalFeeSupplement) }}<br /><br />{{ text: this.conversion(this.allTotal.totalFeeSupplement) }}</p>
        } else if (column.label == '最低运费（元）') {
          el = <p>{{ text: this.conversion(this.currentTotal.totalFeeMin) }}<br /><br />{{ text: this.conversion(this.allTotal.totalFeeMin) }}</p>
        } else if (column.label == '保险费（元）') {
          el = <p>{{ text: this.conversion(this.currentTotal.totalFeeInsure) }}<br /><br />{{ text: this.conversion(this.allTotal.totalFeeInsure) }}</p>
        } else if (column.label == '税费（元）') {
          el = <p>{{ text: this.conversion(this.currentTotal.totalFeeTax) }}<br /><br />{{ text: this.conversion(this.allTotal.totalFeeTax) }}</p>
        } else if (column.label == '总运费（元）') {
          el = <p>{{ text: this.conversion(this.currentTotal.totalFee) }}<br /><br />{{ text: this.conversion(this.allTotal.totalFee) }}</p>
        } else if (column.label == '总数量（箱）') {
          el = <p>{{ text: this.conversion(this.currentTotal.totalQuantity) }}<br /><br />{{ text: this.conversion(this.allTotal.totalQuantity) }}</p>
        } else if (column.label == '总重量（公斤）' || column.label == '重量（公斤）' || column.label == '总重量（吨）') {
          el = <p>{{ text: this.conversion(this.currentTotal.totalWeight) }}<br /><br />{{ text: this.conversion(this.allTotal.totalWeight) }}</p>
        } else if (column.label == '总体积（方）' || column.label == '体积（方）') {
          el = <p>{{ text: this.conversion(this.currentTotal.totalVolume) }}<br /><br />{{ text: this.conversion(this.allTotal.totalVolume) }}</p>
        }
        if (this.menuId == 313 || this.menuId == 327) {
          el = <p>{{ text: this.conversion(value) }}<br /><br />{{ text: this.conversion(values) }}</p>
        }
        sums[index] = el
        return;
      });
      return sums;
    },
    transitionText (val, rmsData, textName) {
      let value
      let item = val
      let text = val[rmsData][textName]
      if ((textName == 'totalVolume' || textName == 'totalWeight') &&
        textName != 'profits') {
        value = text ? this.conversion(text) : '0.00'
      } else if ((rmsData == 'cost' || rmsData == 'fee') &&
        textName != 'profits') {
        value = text ? this.conversion(text) : '0.00'
      } else if (textName == 'profits') {
        let vals = (Number(item.cost.amountIncome) - Number(item.cost.amountCost)).toFixed(4).replace(/\d(?=(\d{3})+\.)/g, '$&,')
        value = vals.substring(0, vals.length - 2);
      } else if (textName == 'countScoreRate') {
        value = text ? text.toFixed(1) : '0.0'
      } else if (rmsData == 'rate') {
        value = this.digitalConversion(text)
      } else {
        value = text ? this.conversion(text) : 0
      }
      return value
    },
    digitalConversion (data) {
      let value
      if (data == 100) {
        value = data + '%'
      } else if (data == 0 || !data) {
        value = '0%'
      } else {
        value = data + '%'
      }
      return value
    },
    recordRms () {
      setTimeout(() => {
        if (this.menuId == 333 || this.menuId == 334) {
          this.recordRmsNewFilters({ userId: this.userId, menuId: this.menuId, data: {} })
          this.recordRmsNewFilters({ userId: this.userId, menuId: this.menuId, data: JSON.parse(JSON.stringify(this.params)) })
        }
      }, 200)
    }
  },
  updated () {
    this.$nextTick(() => {
      this.$refs.tableData.doLayout();
    })
  },
  components: {
    RmsDetail,
    ExportExcelAction
  },
  watch: {
    params: {
      handler (newVal, oldVal) {
        this.recordRms()
      },
      deep: true
    }
  }
};